home *** CD-ROM | disk | FTP | other *** search
/ Tech Arsenal 1 / Tech Arsenal (Arsenal Computer).ISO / tek-04 / netprog.zip / NETPROG.TAR / lock / lockv7.c < prev    next >
C/C++ Source or Header  |  1989-12-17  |  912b  |  49 lines

  1. /*
  2.  * Locking routines using the link() system call.
  3.  */
  4.  
  5. #define    LOCKFILE    "seqno.lock"
  6.  
  7. #include    <sys/errno.h>
  8. extern int    errno;
  9.  
  10. my_lock(fd)
  11. int    fd;
  12. {
  13.     int    tempfd;
  14.     char    tempfile[30];
  15.  
  16.     sprintf(tempfile, "LCK%d", getpid());
  17.  
  18.     /*
  19.      * Create a temporary file, then close it.
  20.      * If the temporary file already exists, the creat() will
  21.      * just truncate it to 0-length.
  22.      */
  23.  
  24.     if ( (tempfd = creat(tempfile, 0444)) < 0)
  25.         err_sys("can't creat temp file");
  26.     close(tempfd);
  27.  
  28.     /*
  29.      * Now try to rename the temporary file to the lock file.
  30.      * This will fail if the lock file already exists (i.e., if
  31.      * some other process already has a lock).
  32.      */
  33.  
  34.     while (link(tempfile, LOCKFILE) < 0) {
  35.         if (errno != EEXIST)
  36.             err_sys("link error");
  37.         sleep(1);
  38.     }
  39.     if (unlink(tempfile) < 0)
  40.         err_sys("unlink error for tempfile");
  41. }
  42.  
  43. my_unlock(fd)
  44. int    fd;
  45. {
  46.     if (unlink(LOCKFILE) < 0)
  47.         err_sys("unlink error for LOCKFILE");
  48. }
  49.